import 'package:flutter/material.dart';
import '../services/user_log_service.dart';
import '../models/user_model.dart';

class LogViewScreen extends StatefulWidget {
  const LogViewScreen({Key? key}) : super(key: key);

  @override
  State<LogViewScreen> createState() => _LogViewScreenState();
}

class _LogViewScreenState extends State<LogViewScreen> {
  late Future<List<UserLog>> _logsFuture;

  @override
  void initState() {
    super.initState();
    _logsFuture = UserLogService.getLogs();
  }

  Future<void> _refreshLogs() async {
    setState(() {
      _logsFuture = UserLogService.getLogs();
    });
  }

  Future<void> _clearLogs() async {
    await UserLogService.clearLogs();
    await _refreshLogs();
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('日志已清空')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('切后台日志'),
        backgroundColor: Colors.deepOrange,
        foregroundColor: Colors.white,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: _refreshLogs,
            tooltip: '刷新',
          ),
          IconButton(
            icon: const Icon(Icons.delete),
            onPressed: _clearLogs,
            tooltip: '清空日志',
          ),
        ],
      ),
      body: FutureBuilder<List<UserLog>>(
        future: _logsFuture,
        builder: (context, snapshot) {
          if (!snapshot.hasData) {
            return const Center(child: CircularProgressIndicator());
          }
          final logs = snapshot.data!..sort((a, b) => b.timestamp.compareTo(a.timestamp));
          if (logs.isEmpty) {
            return const Center(child: Text('暂无日志'));
          }
          return ListView.separated(
            itemCount: logs.length,
            separatorBuilder: (_, __) => const Divider(height: 1),
            itemBuilder: (context, i) {
              final log = logs[i];
              return ListTile(
                leading: Icon(
                  log.action == 'background' ? Icons.arrow_downward : Icons.arrow_upward,
                  color: log.action == 'background' ? Colors.red : Colors.green,
                ),
                title: Text(log.userName),
                subtitle: Text('${log.page}\n${log.action == 'background' ? '切到后台' : '回到前台'}'),
                trailing: Text(
                  '${log.timestamp.hour.toString().padLeft(2, '0')}:${log.timestamp.minute.toString().padLeft(2, '0')}\n${log.timestamp.month.toString().padLeft(2, '0')}-${log.timestamp.day.toString().padLeft(2, '0')}',
                  textAlign: TextAlign.right,
                  style: const TextStyle(fontSize: 12, color: Colors.grey),
                ),
                isThreeLine: true,
              );
            },
          );
        },
      ),
    );
  }
} 